<template>
  <div class="article-list">
    <van-pull-refresh v-model="isRefreshLoading" @refresh="onRefresh"  :success-text="successText">
        <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
            :error.sync="error"
            error-text="请求失败，点击重新加载"
            >
            <!-- <van-cell v-for="(article,index) in list" :key="index" :title="article.title" /> -->
            <ArticleItem v-for="(article,index) in list" :key="index" :article="article" @gotoArticle="$router.push({name:'article',params:{articleId:article.art_id}})"/>
        </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false, // 加载中状态
      finished: false, // 数据加载完成
      timestamp: null, // 获取请求下一页数据
      error: false,
      // 下拉刷新组件需要的参数
      successText: '刷新成功',
      isRefreshLoading: false
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    // 初始化或者滚动到底部的时候会触发onLoad函数
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })

        // 测试请求失败
        // if (Math.random() > 0.5) {
        //   JSON.parse('wjqkh')
        // }
        const { results, pre_timestamp: timer } = data.data
        this.list = [...this.list, ...results]
        // 加载状态结束
        this.loading = false
        if (!results.length) {
          this.finished = true
          return
        }
        this.timestamp = timer
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },
    // 下拉刷新会调用并触发该函数
    async onRefresh () {
    // 异步操作
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        // 测试请求失败
        // if (Math.random() > 0.2) {
        //   JSON.parse('wjqkh')
        // }
        const { results } = data.data
        this.list = [...results, ...this.list]
        this.isRefreshLoading = false
        this.successText = `刷新成功,刷新了${results.length}条数据`
      } catch (err) {
        this.isRefreshLoading = false
        this.successText = '刷新失败'
      }
    //   this.$toast('刷新成功')
    //   this.isLoading = false
    }
  }
}
</script>

<style scoped lang="less">
    //让每一个滚动列表有自己的滚动内容
    .article-list{
        height: 79vh;
        overflow-y: auto;
    }
</style>
